﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API.Models.Repository
{
    public class Companies_Repository : GenericRepository<PartnerDbContext, WH_COMPANIES>
    {
        public override IQueryable<WH_COMPANIES> Find(System.Linq.Expressions.Expression<Func<WH_COMPANIES, bool>> predicate)
        {
            IQueryable<WH_COMPANIES> query =
                _entities.SEC_COMPANIES_ACCESS
                    .Include("COMPANY")
                    .Where(r => r.ALLOW_TO_GUID == session.COMPANY_GUID)
                    .Select(r => r.COMPANY);

            /// Фильтрация по заданному условию
            if (predicate != null)
                query = query.Where(predicate);

            return query;
        }

        public override void Add(WH_COMPANIES entity)
        {
            if (entity.GUID_RECORD == null || entity.GUID_RECORD == Guid.Empty)
                entity.GUID_RECORD = Guid.NewGuid();

            /// Добавить компанию
            this.Context.Database.ExecuteSqlCommand(
                "EXEC [dbo].[USP_ADD_COMPANY] @GUID_RECORD, @COMPANY_NAME, @EXT_KEY, @OWNER, @NOTE",
                new System.Data.SqlClient.SqlParameter("GUID_RECORD", entity.GUID_RECORD),
                new System.Data.SqlClient.SqlParameter("COMPANY_NAME", entity.COMPANY_NAME),
                new System.Data.SqlClient.SqlParameter("EXT_KEY", entity.EXT_KEY),
                new System.Data.SqlClient.SqlParameter("OWNER", entity.OWNER_GUID.HasValue ? entity.OWNER_GUID.Value : Guid.Empty),
                new System.Data.SqlClient.SqlParameter("NOTE", String.IsNullOrEmpty(entity.NOTE) ? String.Empty : (entity.NOTE)));

            /// Добавить разрешение
            var repository = new SEC_USER_COMPANIES_Repository();

            repository.Add(new SEC_USER_COMPANIES
            {
                ALLOW_TO_GUID = entity.GUID_RECORD,
                GUID_RECORD = Guid.NewGuid(),
                IS_ALLOWED = true,
                SECURITY_CODE = "0000", 
                USER_GUID = this.session.USER_GUID
            });

            repository.Save();
        }
    }
}